package org.example.filter;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Description:过滤器类
 * Author: Amao
 * Date: 2023/5/25
 */
@Component
@WebFilter(urlPatterns = "/user/list")
public class MyFilter implements Filter {

    @Override
    public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

        // 获取URL信息，判断是否需要过滤
        String requestURI = httpRequest.getRequestURI();
        if(!requestURI.contains("/user/list")){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        // 判断permissionId是否正常传入
        HttpSession session = httpRequest.getSession();
        Object permissionIdParam = session.getAttribute("permission_id");
        int permissionId;
        if(permissionIdParam != null){
            permissionId = (int) permissionIdParam;
        }else{
            permissionId = 0;
        }

        // 根据不同的权限，返回不同的响应内容
        String responseMessage = "";
        if(permissionId == 0){
            responseMessage = "Permission denied! Please login first!";
            PrintWriter writer = httpResponse.getWriter();
            writer.write(responseMessage);
        }else if(permissionId == 1){
            // 放行
            filterChain.doFilter(servletRequest, servletResponse);
        }else if(permissionId == 2){
            responseMessage = "You do not have access to this page! You are being redirected to the user page"
                    + "<meta http-equiv='refresh' content='3;url="+session.getAttribute("path")+"'>";
            httpResponse.setContentType("text/html");
            PrintWriter writer = httpResponse.getWriter();
            writer.write(responseMessage);
        }

    }
}
